package com.example.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.ItemAndGroup;
import com.example.entity.ItemGroup;
import com.example.mapper.ItemAndGroupMapper;
import com.example.mapper.ItemGroupMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class ItemGroupService extends ServiceImpl<ItemGroupMapper, ItemGroup> {

    @Resource
    private ItemGroupMapper itemGroupMapper;

    @Resource
    private ItemAndGroupMapper itemAndGroupMapper;

    @Transactional //添加事务的注解 怕2张表  一张表添加成功  而另外一张表添加失败
    public void add(String itemids, ItemGroup itemGroup) {

        // 先添加第一张表 itemGroup 表
        int insert = itemGroupMapper.insert(itemGroup);
        System.out.println("insert = " + insert);


        //添加第二张表 itemAndGroup中间表
        Long groupId = itemGroup.getId();

        //用string按，截取出来
        String[] ids = itemids.split(",");

        for (String id : ids) {
            ItemAndGroup itemAndGroup = new ItemAndGroup();
            itemAndGroup.setGroupId(groupId);
            itemAndGroup.setItemId(Long.parseLong(id));
            itemAndGroupMapper.insert(itemAndGroup);
        }

    }

}